package com.hmkj.admin.controller.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.admin.utils.AdminSessionHelper;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.entity.export.ExportUtils;
import com.hmkj.common.utils.PriceHelper;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.Enum;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.account.AccountLogModel;
import com.hmkj.core.model.user.UserBankModel;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.order.Order;
import com.hmkj.core.po.seller.Seller;
import com.hmkj.core.po.system.Admin;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.account.AccountLogService;
import com.hmkj.core.service.order.OrderService;
import com.hmkj.core.service.system.AdminService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.core.service.userBank.UserBankService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Controller
@RequestMapping(BaseController.BASE_URI)
public class UserJsonController extends GenericController<Integer, User> {
    @Resource
    private UserService userService;
    @Resource
    AdminService adminService;
    @Resource
    private OrderService orderService;
    @Resource
    private UserBankService userBankService;
    @Resource
    private AccountLogService accountLogService;


    private User checkPrimaryKey(Integer id) throws Exception {
        if (null == id) {
            throw new BussinessException("参数有误");
        } else {
            User user = userService.selectByPrimaryKey(id);
            if (null != user) {
                return user;
            } else {
                throw new BussinessException("参数有误");
            }
        }
    }


    /**
     * 客户列表列表json数据
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/list.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:user:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (admin.getRoleId() == Enum.ONE_ROLE_ID || admin.getRoleId() == Enum.TWO_ROLE_ID || admin.getRoleId() == Enum.THREE_ROLE_ID
                || admin.getRoleId() == Enum.NEXT_SELLER_ROLE_ID || admin.getRoleId() == Enum.AGENT_SELLER_ROLE_ID) {
            User user = userService.selectByPrimaryKey(admin.getUserId());
            List<User> userList = userService.listPartnerByLevel(user.getCode(), 0);
            String userIds = "0";
            if (CollectionUtils.isNotEmpty(userList)) {
                userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
            }
            ObjectMapper mapper = new ObjectMapper();
            DtGrid dtGrid1 = mapper.readValue(dtGridPager, DtGrid.class);
            Map<String, Object> dtGridFastQueryParameters = dtGrid1.getFastQueryParameters();
            dtGridFastQueryParameters.put("in_id", userIds);
            dtGrid1.setFastQueryParameters(dtGridFastQueryParameters);
            dtGridPager = dtGrid1.toJsonString();
        }
        dtGrid = userService.getDtGridList(dtGridPager, UserModel.class);
        return dtGrid;
    }

    /**
     * 添加投资人
     */
    @RequestMapping(value = "/user/addInvest.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:user:addInvest")
    public ResultEntity addInvest(Integer id, BigDecimal feeScale) throws Exception {
        User user = checkPrimaryKey(id);
        if (null == feeScale) {
            throw new BussinessException("参数有误");
        }
        if (!ValidateUtils.isPrice(feeScale.toString())) {
            throw new BussinessException("佣金格式有误");
        }
        if (feeScale.compareTo(BigDecimal.ZERO) == -1 || feeScale.compareTo(new BigDecimal(100)) == 1) {
            throw new BussinessException("佣金比例应在0~100之间");
        }
        Admin admin = adminService.selectOne(new Admin(t -> {
            t.setName(user.getMobilePhone());
        }));
        if (admin != null) {
            throw new BussinessException("用户名已经存在");
        }
        adminService.addAdminInvest(user, feeScale);
        return ok();
    }

    /**
     * 添加销售
     */
    @RequestMapping(value = "/user/addSeller.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:user:addSeller")
    public ResultEntity addSeller(UserModel userModel) throws Exception {
        User user = checkPrimaryKey(userModel.getId());
        if (null == userModel.getFeeScale()) {
            throw new BussinessException("参数有误");
        }
        if (!ValidateUtils.isPrice(userModel.getFeeScale().toString())) {
            throw new BussinessException("佣金格式有误");
        }
        if (userModel.getFeeScale().compareTo(BigDecimal.ZERO) == -1 || userModel.getFeeScale().compareTo(new BigDecimal(100)) == 1) {
            throw new BussinessException("佣金比例应在0~100之间");
        }
        if (StringUtils.isBlank(userModel.getAllCustomer().toString()) || userModel.getAllCustomer() != Seller.ALLCUSTOMER.T1.code || userModel.getAllCustomer() != Seller.ALLCUSTOMER.T2.code) {
            throw new BussinessException("是否可以查看所有用户状态有误");
        }
        if (StringUtils.isBlank(userModel.getCustomerPhone().toString()) || userModel.getCustomerPhone() != Seller.CUSTOMERPHONE.T1.code || userModel.getCustomerPhone() != Seller.CUSTOMERPHONE.T2.code) {
            throw new BussinessException("是否可以查看客户电话状态有误");
        }
        Admin aa = adminService.selectOne(new Admin(t -> {
            t.setName(user.getMobilePhone());
        }));
        if (aa != null) {
            throw new BussinessException("用户名已经存在");
        }
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (user.getUserType() == Enum.UserType.USER.getValue()) {
            if (admin.getRoleId() == Enum.PLATFORM_ROLE_ID || admin.getRoleId() == Enum.SELLER_ROLE_ID) {
                userModel.setUserType(Enum.UserType.NEXTSELLER.getValue());
            } else if (admin.getRoleId() == Enum.ONE_ROLE_ID || admin.getRoleId() == Enum.TWO_ROLE_ID || admin.getRoleId() == Enum.THREE_ROLE_ID) {
                userModel.setUserType(Enum.UserType.AGENTSELLER.getValue());
            }
            userModel.setCode(user.getCode());
            userModel.setLevel(user.getLevel());
            userModel.setInviteId(user.getInviteId());
            adminService.addAdminSeller(userModel, admin);
        }
        return ok();
    }

    /**
     * 重置密码
     */
    @RequestMapping(value = "/user/pwdReset.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:user:pwdReset")
    public ResultEntity pwdReset(Integer id) throws Exception {
        if (id == null || id <= 0) {
            throw new BussinessException("参数有误");
        }
        userService.resetPwd(id);
        return ok();
    }

    /**
     * 修改邀请人
     */
    @RequestMapping(value = "user/changeInvest.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:user:cgInvest")
    public ResultEntity changeInvestor(Integer id, Integer inviteId) throws Exception {
        userService.editInvestor(id, inviteId);
        return ok();
    }

    /**
     * 代理商列表
     */
    @RequestMapping(value = "/agent/list.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:agent:list")
    public DtGrid agentListJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = userService.getDtGridList(dtGridPager, UserModel.class);
        //查找上级代理商
        List<Object> list = dtGrid.getExhibitDatas();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Object obj : list) {
                LinkedHashMap user = (LinkedHashMap) obj;
                //上级代理商
                Integer level = (int) user.get("level");
                Integer parentId = (int) user.get("inviteId");
                Integer userType = (int) user.get("userType");
                User parentUser = null;

                if (null != parentId && userType != Enum.UserType.ONELEVEL.getValue() && userType != Enum.UserType.NEXTSELLER.getValue()) {
                    if (level > 1) {
                        //上级
                        for (int i = level - 1; i > 0; i--) {
                            parentUser = userService.selectByPrimaryKey(parentId);
                            Integer p = parentUser.getUserType();
                            if (parentUser != null && (p == Enum.UserType.ONELEVEL.getValue() || p == Enum.UserType.TWOLEVEL.getValue() || p == Enum.UserType.THREELEVEL.getValue())) {
                                user.put("investName", parentUser.getUserName());
                                break;
                            }
                            parentId = parentUser.getInviteId();
                        }
                    }
                }
            }
        }
        return dtGrid;
    }

    /**
     * 添加代理商
     */
    @ResponseBody
    @RequestMapping("/agent/add.json")
    public ResultEntity addAgent(User user) throws Exception {
        //设置为代理商
        if (StringUtils.isBlank(user.getId())) {
            throw new BussinessException("请选择代理商");
        }
        if (StringUtils.isBlank(user.getPoundageScale())) {
            throw new BussinessException("手续费分佣比例不能为空");
        }
        if (StringUtils.isBlank(user.getProfitScale())) {
            throw new BussinessException("利润分佣比例不能为空");
        }
        if (StringUtils.isBlank(user.getDeferScale())) {
            throw new BussinessException("递延费分佣比例不能为空");
        }
        User u = userService.selectByPrimaryKey(user.getId());
        if (u != null && u.getUserType() == Enum.UserType.USER.getValue()) {
            Admin admin = AdminSessionHelper.getCurrAdmin();
            if (admin.getRoleId() == Enum.PLATFORM_ROLE_ID || admin.getRoleId() == Enum.SELLER_ROLE_ID) {
                if (PriceHelper.isGreaterThan(user.getPoundageScale(), new BigDecimal(100))) {
                    throw new BussinessException("综合管理费分佣比例不能超出100%");
                } else if (PriceHelper.isGreaterThan(user.getProfitScale(), new BigDecimal(100))) {
                    throw new BussinessException("利润分佣比例不能超出100%");
                } else if (PriceHelper.isGreaterThan(user.getDeferScale(), new BigDecimal(100))) {
                    throw new BussinessException("递延费分佣比例不能超出100%");
                }
                u.setUserType(Enum.UserType.ONELEVEL.getValue());
            } else if (admin.getRoleId() == Enum.ONE_ROLE_ID) {
                u.setUserType(Enum.UserType.TWOLEVEL.getValue());
                User user1 = userService.selectByPrimaryKey(admin.getUserId());
                if (PriceHelper.isGreaterThan(user.getPoundageScale(), user1.getPoundageScale())) {
                    throw new BussinessException("综合管理费分佣比例不能超出上级比例");
                } else if (PriceHelper.isGreaterThan(user.getProfitScale(), user1.getProfitScale())) {
                    throw new BussinessException("利润分佣比例不能超出上级比例");
                } else if (PriceHelper.isGreaterThan(user.getDeferScale(), user1.getDeferScale())) {
                    throw new BussinessException("递延费分佣比例不能超出上级比例");
                }
            } else if (admin.getRoleId() == Enum.TWO_ROLE_ID) {
                u.setUserType(Enum.UserType.THREELEVEL.getValue());
                User user1 = userService.selectByPrimaryKey(admin.getUserId());
                if (PriceHelper.isGreaterThan(user.getPoundageScale(), user1.getPoundageScale())) {
                    throw new BussinessException("综合管理费分佣比例不能超出上级比例");
                } else if (PriceHelper.isGreaterThan(user.getProfitScale(), user1.getProfitScale())) {
                    throw new BussinessException("利润分佣比例不能超出上级比例");
                } else if (PriceHelper.isGreaterThan(user.getDeferScale(), user1.getDeferScale())) {
                    throw new BussinessException("递延费分佣比例不能超出上级比例");
                }
            } else {
                throw new BussinessException("无权限添加代理商");
            }
            u.setPoundageScale(user.getPoundageScale());
            u.setProfitScale(user.getProfitScale());
            u.setDeferScale(user.getDeferScale());
        }
        userService.addAdminAgent(u);
        return ok();
    }

    /**
     * 我的代理商
     */
    @RequestMapping(value = "/agent/myList.json", method = RequestMethod.POST)
    @ResponseBody
    @RequiresPermissions("sys:myAgent:list")
    public DtGrid myAgentListJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (admin.getRoleId() == Enum.PLATFORM_ROLE_ID || admin.getRoleId() == Enum.SELLER_ROLE_ID) {
            dtGrid = userService.getDtGridList(dtGridPager, UserModel.class);
        } else {
            dtGrid = findByPage(dtGridPager, admin);
        }
        return dtGrid;
    }


    /**
     * 查询下级代理商
     *
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    public DtGrid findByPage(String dtGridPager, Admin admin) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        DtGrid dtGrid = mapper.readValue(dtGridPager, DtGrid.class);
        Map<String, Object> dtGridFastQueryParameters = dtGrid.getFastQueryParameters();
        if (admin.getType() == Enum.SELLER_TYPE) {
            dtGridFastQueryParameters.put("eq_user_type", Enum.UserType.ONELEVEL.getValue());
        } else if (admin.getType() == Enum.ONE_TYPE) {
            dtGridFastQueryParameters.put("eq_user_type", Enum.UserType.TWOLEVEL.getValue());
        } else if (admin.getType() == Enum.TWO_TYPE) {
            dtGridFastQueryParameters.put("eq_user_type", Enum.UserType.THREELEVEL.getValue());
        } else {
            throw new BussinessException("当前登录用户无权限查看");
        }
        User user = userService.selectByPrimaryKey(admin.getUserId());
        List<User> userList = userService.listPartnerByLevel(user.getCode(), 0);
        String userIds = "0";
        if (CollectionUtils.isNotEmpty(userList)) {
            userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
        }
        dtGridFastQueryParameters.put("in_id", userIds);
        dtGrid.setFastQueryParameters(dtGridFastQueryParameters);
        String dtGridPagers = dtGrid.toJsonString();
        return userService.getDtGridList(dtGridPagers, UserModel.class);
    }


    /**
     * 获取当前登录代理商下级可以设置为代理商的用户
     */
    @ResponseBody
    @RequestMapping(value = "/agent/subordinat.json", method = RequestMethod.POST)
//    @RequiresPermissions("sys:agent:subordinat")
    public DtGrid subListJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        if (admin.getRoleId() == Enum.PLATFORM_ROLE_ID || admin.getRoleId() == Enum.SELLER_ROLE_ID) {
            dtGrid = userService.getDtGridList(dtGridPager, UserModel.class);
        } else {
            dtGrid = findSubByPage(dtGridPager, admin);
        }
        return dtGrid;
    }

    /**
     * 查询当前代理商下级用户
     *
     * @param dtGridPager
     * @return
     * @throws Exception
     */
    public DtGrid findSubByPage(String dtGridPager, Admin admin) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        DtGrid dtGrid = mapper.readValue(dtGridPager, DtGrid.class);
        Map<String, Object> dtGridFastQueryParameters = dtGrid.getFastQueryParameters();
        if (admin.getType() != Enum.ONE_TYPE && admin.getType() != Enum.TWO_TYPE && admin.getType() != Enum.THREE_TYPE && admin.getType() != Enum.SELLER_TYPE) {
            throw new BussinessException("当前登录用户无权限查看");
        }
        User user = userService.selectByPrimaryKey(admin.getUserId());
        List<User> userList = userService.listPartnerByLevel(user.getCode(), 0);
        String userIds = "0";
        if (CollectionUtils.isNotEmpty(userList)) {
            userIds = userList.stream().map(param -> param.getId().toString()).collect(Collectors.joining(","));
        }
        dtGridFastQueryParameters.put("in_id", userIds);
        dtGrid.setFastQueryParameters(dtGridFastQueryParameters);
        String dtGridPagers = dtGrid.toJsonString();
        return userService.getDtGridList(dtGridPagers, UserModel.class);
    }

    /**
     * 结算报表
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/profitReport.json", method = RequestMethod.POST)
    @RequiresPermissions("sys:user:profit")
    public DtGrid profitReportJson(String dtGridPager) throws Exception {
        DtGrid dtGrid = new DtGrid();
        Admin admin = AdminSessionHelper.getCurrAdmin();
        ObjectMapper mapper = new ObjectMapper();
        dtGrid = mapper.readValue(dtGridPager, DtGrid.class);
        dtGrid = userService.getProfitReportl(dtGrid, admin);
        return dtGrid;
    }


    /**
     * 用户对应的订单
     */
    @RequestMapping(value = "/user/order.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid userOrder(String dtGridPager) throws Exception {
        return orderService.getDtGridList(dtGridPager, Order.class);
    }

    /**
     * 客户列表列表json数据
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/user/list1.json", method = RequestMethod.POST)
    public DtGrid userListJson(String dtGridPager) throws Exception {
        return userService.getDtGridList(dtGridPager, User.class);
    }

    /**
     * 列表导出
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "user/json/export", method = RequestMethod.POST)
    public ResultEntity export(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        ExportUtils.export(request, response, userService.getDtGridListExport(dtGridPager));
        return ok();
    }


    /**
     * 修改用户名
     *
     * @param id
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateUserName")
    @RequiresPermissions("sys:user:username:edit")
    public ResultEntity updateUserName(Integer id, String userName) throws Exception {
        if (null == id) {
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(userName)) {
            throw new BussinessException("用户名不能为空");
        } else if (userName.length() > 50) {
            throw new BussinessException("用户名长度不能大于50位！");
        } else if (!ValidateUtils.isUserName(userName)) {
            throw new BussinessException("用户名必须是中英文或数字组合");
        }
        User user = userService.selectByPrimaryKey(id);
        if (StringUtils.isNotBlank(user.getUserName())) {
            if (user.getUserName().equals(userName)) {
                return ok();
            }
        }
        int count = userService.selectCount(new User(t -> {
            t.setUserName(userName);
            t.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (count > 0) {
            throw new BussinessException("该用户名已存在");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setUserName(userName);
        }));
        return ok();
    }


    /**
     * 修改用户姓名
     *
     * @param id
     * @param realName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateRealName")
    @RequiresPermissions("sys:user:realname:edit")
    public ResultEntity updateRealName(Integer id, String realName) throws Exception {
        if (!StringUtils.isNotBlank(id)) {
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(realName)) {
            throw new BussinessException("真实姓名不能为空");
        } else if (realName.length() > 20) {
            throw new BussinessException("真实姓名长度不能大于20个字符");
        }
//        userService.updateByPrimaryKeySelective(new User(u -> {
//            u.setId(id);
//            u.setRealName(realName);
//        }));
        return ok();
    }

    /**
     * 修改用户身份证
     *
     * @param id
     * @param idCard
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateIdCard")
    @RequiresPermissions("sys:user:idcard:edit")
    public ResultEntity upateIdCard(Integer id, String idCard) throws Exception {
        if (!StringUtils.isNotBlank(id)) {
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(idCard)) {
            throw new BussinessException("身份证号码不能为空");
        } else if (idCard.length() < 15 || idCard.length() > 18) {
            throw new BussinessException("身份证号码长度限制在15到18个字符");
        } else if (!ValidateUtils.isCard(idCard)) {
            throw new BussinessException("身份证号码格式不正确");
        }
//        User user = userService.selectByPrimaryKey(id);
//        if(StringUtils.isNotBlank(user.getIdCard())){
//            if(user.getIdCard().equals(idCard)){
//                return ok();
//            }
//        }
//        int count = userService.selectCount(new User(t->{
//            t.setIdCard(idCard);
//            t.setDelFlag(User.DELFLAG.NORMAL.code);
//        }));
//        if(count>0){
//            throw new BussinessException("身份证号码已存在，请核对身份证号码是否正确");
//        }
//        userService.updateByPrimaryKeySelective(new User(u -> {
//            u.setId(id);
//            u.setIdCard(idCard);
//        }));
        return ok();
    }

    /**
     * 用户下线列表
     */
    @RequestMapping(value = "/user/userInvestor.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid userInvestor(String dtGridPager) throws Exception {
        return userService.getDtGridList(dtGridPager, User.class);
    }

    /**
     * 我的银行
     */
    @RequestMapping(value = "/user/myBank.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid myBank(String dtGridPager) throws Exception {
        return userBankService.getDtGridList(dtGridPager, UserBankModel.class);
    }

    /**
     * 资金明细
     */
    @RequestMapping(value = "/user/moneyDetails.json", method = RequestMethod.POST)
    @ResponseBody
    public DtGrid moneyDetail(String dtGridPager) throws Exception {
        return accountLogService.getDtGridList(dtGridPager, AccountLogModel.class);
    }
}